package com.foo.LoadingData;

import java.io.DataInputStream;
import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.foo.constants.UIMessages;


/**
 * Servlet implementation class LoadData
 */
public class LoadData extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private int startPos,endPos;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoadData() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession(true);
		try
		{
			byte[] fileData = storeFileLocally(request,response);
			
			if(fileData == null)
			{
				session.setAttribute("ServerMessage", UIMessages.INVALID_FILE);
				RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/upload.jsp");
				dispatcher.forward(request, response);
			}
			System.out.println("Byte data obtained");
			String data = LoadFile.loadFile(fileData, startPos, endPos);
			if(data != null)
			{
				RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/uploadRedirect.jsp");
				dispatcher.forward(request, response);
			}
			else
			{
				session.setAttribute("ServerMessage", UIMessages.SERVICE_UNAVAILABLE);
				RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/upload.jsp");
				dispatcher.forward(request, response);
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
			session.setAttribute("ServerMessage", UIMessages.SERVICE_UNAVAILABLE);
			RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/upload.jsp");
			dispatcher.forward(request, response);
		}		
	}
	
	private byte[] storeFileLocally(HttpServletRequest request,HttpServletResponse response) throws Exception
	{
		String contentType = request.getContentType();
		HttpSession session = request.getSession(true);
		try
		{
			if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) 
			{
				DataInputStream in = new DataInputStream(request.getInputStream());
				//we are taking the length of Content type data                
				int dataLength = request.getContentLength();                
				byte dataBytes[] = new byte[dataLength];          
				
				int byteRead = 0;                
				int totalBytesRead = 0;                
				//this loop converting the uploaded file into byte code                
				while (totalBytesRead < dataLength) 
				{                        
					byteRead = in.read(dataBytes, totalBytesRead, dataLength);                        
					totalBytesRead += byteRead;                        
				}                                        
				String file = new String(dataBytes);                
				//for saving the file name                
				String saveFile = file.substring(file.indexOf("filename=\"") + 10);                
				saveFile = saveFile.substring(0, saveFile.indexOf("\n"));                
				saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1,saveFile.indexOf("\""));
				//Check for proper Input file
				String fileNames = saveFile.substring(saveFile.indexOf("."), saveFile.length());
				if(!fileNames.equalsIgnoreCase(".txt"))
				{
					session.setAttribute("ServerMessage", UIMessages.INVALID_FILE);
					RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/upload.jsp");
					dispatcher.forward(request, response);	
				}
			
				int lastIndex = contentType.lastIndexOf("=");                
				String boundary = contentType.substring(lastIndex + 1,contentType.length());                
				int pos;                
				//extracting the index of file                 
				pos = file.indexOf("filename=\"");                
				pos = file.indexOf("\n", pos) + 1;                
				pos = file.indexOf("\n", pos) + 1;                
				pos = file.indexOf("\n", pos) + 1;                
				int boundaryLocation = file.indexOf(boundary, pos) - 4;                
				startPos = ((file.substring(0, pos)).getBytes()).length;                
				endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;                
				return dataBytes;
			}
			else
			{
				session.setAttribute("ServerMessage", UIMessages.SELECT_FILE);
				RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/upload.jsp");
				dispatcher.forward(request, response);
				return null;
			}			
		}
		catch(Exception e)
		{
			throw e;
		}
	}

}
